import {
  behavior as computedBehavior
} from 'miniprogram-computed';
const {
  funList
} = require("./funList");
let likeSet = new Set();
// const behaviorTest = require('./behavior')
Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    loadShow: [1, 1, 1],
    loginDisable: false,
    isShow: true,
    navTop: 0,
    topCa: ["推荐", "主页", "消息"],
    funList,
    swiperMessage: [],
    currentIndex: 1,
    heightConfig: 0,
    widthConfig: 0,
    userInfo: null, //用户信息
    userId: "", //用户id
    new_article: [], //最新的几篇文章
    new_end: false, //是否加载完成
    new_page: 1, //当前page页数
    themeMessage: [], //主题信息

    //精选文章
    new_likeArticle: [], //最新的几篇文章
    new_likeArticle_end: false, //是否加载完成
    new_likeArticle_page: 1, //当前page页数
    //刷新栏目
    hideHeader: true,
    refreshTime: '', // 刷新的时间 
    /**
     * 下拉
     */
    height: 0, // scroll-wrap 的高度，这个高度是固定的
    inner_height: 0, // inner-wrap 的高度，这个高度是动态的
    scroll_top: 0, // 滚动到位置。
    start_scroll: 0, // 滚动前的位置。
    touch_down: 0, // 触摸时候的 Y 的位置

    /**
     * 新消息
     */
    new_notice: [],
    new_notice_end: false, //是否加载完成
    new_notice_page: 1, //当前page页数
    notice_type: ["私信", "喜欢", "评论", "回复", "系统"],
    notice_type_message: ["", "我喜欢你的这篇文章,点击查看~", "", "", ""],
    canIUseGetUserProfile: false,



    campusId: 1,
    campusLogo: "",
    campusName: "",
    totalArticle: 0,
    totalUser: 0
  },
  watch: {
    'loadShow.**': (newValue) => {
      // if (!newValue.filter) return;
      if (!newValue.filter(i => i).length) {
        wx.hideLoading()
      }
    },
    "hideHeader": function (newValue) {
      if (!newValue) return;
      switch (this.data.currentIndex) {
        case 0:
          this.data.new_page = 1;
          this.data.new_end = false;
          this.getNewArticle(1) //获取最新的文章
          break;
        case 2:
          this.data.new_notice_page = 1;
          this.data.new_notice_end = false;
          this.loadNotice(1) //获取最新的消息
          break;
        case 1:
        default:
          this.data.new_likeArticle_page = 1;
          this.data.new_likeArticle_end = false;
          this.getAllLikeArticle(1) //获取精选文章
          break;
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      loadShow: [0, 1, 1]
    })
    if (this.data.loadShow.filter(i => i).length) {
      wx.showLoading({
        title: '加载中',
      })
    }
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    if (this.checkLogin()) {
      console.log("logined")
      getApp().requestWithToken.get("/getUserLikeArticles").then(result => {
        likeSet = getApp().likeSet = new Set(result.data);
        // console.log(likeSet)
        // getApp().Storage.set("likeSet", likeSet);
        // console.log(getApp().Storage.get("likeSet"))
      })
    }
    this.setData({
      navTop: getApp().globalData.navTop,
      heightConfig: getApp().globalData.windowHeight,
      widthConfig: getApp().globalData.windowWidth,
    })
    let that = this;
    this.createSelectorQuery().select('#scroll-wrap').boundingClientRect(res => {
      that.setData({
        height: res.height
      })
    }).exec()
    /**
     * 获取主题
     */
    // getApp().requestWithoutToken.get('/api/getAllTheme').then(result => {
    //   that.setData({
    //     themeMessage: result.data,
    //     "loadShow[0]": 0
    //   })
    //   getApp().Storage.set("themeMessage", result.data);
    // })
    // wx.request({
    //   url: getApp().getDomain() + '/api/getAllTheme',
    //   method: 'GET',
    //   success: (result) => {
    //     that.setData({
    //       themeMessage: result.data.data,
    //       "loadShow[0]": 0
    //     })
    //     getApp().Storage.set("themeMessage", result.data.data);
    //   },
    // });

    /**
     * 获取轮播图
     */
    getApp().requestWithoutToken.get('/api/getSwiperMessage').then(result => {
      that.setData({
        swiperMessage: result.data,
        "loadShow[1]": 0
      })
    });
    this.setData({
      new_end: false,
      new_page: 1,
      new_likeArticle_end: false,
      new_likeArticle_page: 1,
      // new_article: [],
      // new_notice: [],
      new_notice_end: false, //是否加载完成
      new_notice_page: 1, //当前page页数
    })

    this.getAllLikeArticle(1) //获取精选文章
    this.getNewArticle(1) //获取最新的文章
    this.loadNotice(1) //获取最新的消息
    this.setData({
      widthConfig: getApp().globalData.windowWidth,
      heightConfig: getApp().globalData.windowHeight,
    })


    let campusId = getApp().Storage.get("campusId")
    this.refreshSchoolInfo(campusId)


    console.log(options)
    if (options && options.id) {
      this.setData({
        campusId: options.id
      })
      getApp().Storage.set("campusId", options.id)
      this.refreshSchoolInfo(options.id)
    }
  },
  checkUserNoticeMessage(e) {
    wx.showModal({
      title: e.currentTarget.id,
      confirmText: "去看看",
      cancelText: "取消",
      success: res => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/me/me?id=' + e.currentTarget.dataset.userid,
          })
        }
      }
    })
  },
  deleteNotice(e) {
    let that = this;
    wx.showModal({
      title: "提示",
      content: "是否删除这条消息",
      confirmText: "删除",
      success: res => {

        if (res.confirm) {
          wx.showLoading({
            title: '删除中~',
          })
          getApp().requestWithToken.post('/deleteNotice/' + e.currentTarget.id).then(result => {
            if (result.code == 200) {
              wx.showToast({
                title: '删除成功',
              })
              that.onLoad();
            } else {
              wx.showModal({
                title: '提示',
                content: result.msg + '，错误码：' + result.code,
                confirmText: '确定',
                showCancel: false,
              })
            }
          });
        }
      }
    })
  },
  previewImage: function (e) {
    let that = this
    let arr = [];
    let reg = new RegExp('(?<=(src="))[^"]*?(?=")', 'ig')
    let allSrc = that.data.article.match(reg)
    for (let i = 0; i < allSrc.length; i++) {
      arr.push(allSrc[i])
    }
    wx.previewImage({
      current: arr, // 当前显示图片的http链接  
      urls: arr // 需要预览的图片http链接列表  
    })
  },
  //点击轮播图
  touchImage(e) {
    let swiper = this.data.swiperMessage[e.currentTarget.id];
    if (swiper.swiperType == 1) {
      wx.showModal({
        title: '提示',
        content: swiper.intro,
        showCancel: false,
        cancelColor: '#000000',
        confirmText: '确定',
      });
    } else if (swiper.swiperType == 2) {
      this.check_user_message({
        "mark": {
          "id": swiper.userId
        }
      })
    } else if (swiper.swiperType == 3) {
      this.message_detail({
        "currentTarget": {
          "id": swiper.articleId
        }
      })
    } else if (swiper.swiperType == 4) {
      this.toFun({
        "mark": {
          "path": swiper.webUrl
        }
      })
    }
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    this.setData({
      loginDisable: true
    })
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log(res)
        this.getUserInfo.apply(this, [{
          detail: {
            userInfo: res.userInfo
          }
        }])
      },
      fail: () => {
        this.getUserInfo.apply(this, [{
          detail: {
            userInfo: null
          }
        }])
      }
    })
  },
  getUserInfo(e) {
    let that = this;
    if (this.data.loginDisable) {
      this.setData({
        loginDisable: true
      })
    }
    if (e.detail.userInfo == null) {
      wx.showToast({
        title: '取消登录',
        icon: "none"
      })
      this.setData({
        loginDisable: false
      })
      return;
    }
    var listMessage = {
      userNickname: e.detail.userInfo.nickName,
      userGender: e.detail.userInfo.gender, //
      userAvatar: e.detail.userInfo.avatarUrl,
      userCity: e.detail.userInfo.city, //
      userProvince: e.detail.userInfo.province, //
      userCountry: e.detail.userInfo.country, //
    }

    wx.login({
      success: function (result) {
        wx.showLoading({
          title: '登陆中~',
        })
        // 获取登录的临时凭证
        var code = result.code;
        // 调用后端，获取微信的session_key, secret
        getApp().requestWithoutToken.post("/Login?code=" + code, {
          data: listMessage
        }).then(result => {
          if (result.code == 200) {
            wx.showToast({
              title: '登陆成功',
            })
            const {
              userToken,
              isBinding
            } = result.data;
            getApp().Storage.set("token", userToken);
            getApp().Storage.set("isBinding", isBinding);
            getApp().requestWithToken.config.header.authorization = userToken;
            getApp().Storage.set("userInfo", e.detail.userInfo);

            // console.log("result.data.campusId：" + result.data.campusId)
            getApp().Storage.set("campusId", result.data.campusId);
            if (isBinding) {
              that.setData({
                isShow: false,
                // userInfo: e.detail.userInfo
              })
              that.onLoad()
            } else {
              wx.showModal({
                title: '提示',
                content: '尚未绑定教务系统，是否绑定',
                success(res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/bind/bind',
                    })
                  }
                  that.onLoad()
                }
              })
            }
          } else {
            wx.showModal({
              title: '失败',
              content: '出现错误,请联系管理员',
            })
            that.setData({
              loginDisable: true
            })
            return
          }
        })
        // wx.request({
        //   url: getApp().getDomain() + ,
        //   method: "POST",
        //   data: listMessage,
        //   success: function (result) 
        // })
      }
    })
    wx.hideLoading()
  },
  /**
   * 暂不登录
   */
  exit() {
    this.setData({
      isShow: false
    })
  },
  message_detail(e) {
    wx.navigateTo({
      url: '/pages/message_detail/message_detail?article_id=' + e.currentTarget.id,
    });
  },
  swiperChange(e) {
    this.setData({
      currentIndex: e.detail.current
    })
  },
  tapChange(e) {
    this.setData({
      currentIndex: e.currentTarget.id
    })
  },
  comment() {
    wx.navigateTo({
      url: '/pages/comment/comment'
    });
  },
  to_me() {
    var result = this.checkLogin();
    if (result) {
      wx.navigateTo({
        url: '/pages/me/me?id=' + -1
      });
    }
  },
  //查看用户信息
  check_user_message(e) {
    var result = this.checkLogin();
    if (result) {
      wx.navigateTo({
        url: '/pages/me/me?id=' + e.mark.id
      });
    }
  },
  add() {
    var result = this.checkLogin();
    if (result) {
      wx.navigateTo({
        url: '/pages/add/add',
      });
    }
  },
  toFun(e) {
    let that = this;
    // console.log(e)
    let path = e.mark.path;
    if (!path) return;
    if (e.mark.authorization && !this.checkLogin()) {
      return wx.showModal({
        title: "提示",
        content: "该功能需要登录，是否登录？",
        success: (e) => {
          if (e.confirm) {
            that.setData({
              isShow: true,
              loginDisable: false
            })
          } else if (e.cancel) {
            that.setData({
              isShow: false
            })
          }
        }
      })
    }
    wx.navigateTo({
      url: '/pages/function' + path + path, //TODO: 待定
    });

  },
  newArticelLoadMessage() {
    wx.showLoading({
      title: '加载中',
    })
    this.getNewArticle(this.data.new_page + 1)
    wx.hideLoading({})
  },
  likeArticle() {
    wx.showLoading({
      title: '加载中',
    })
    this.getAllLikeArticle(this.data.new_likeArticle_page + 1)
    wx.hideLoading({})
  },
  newNoticeLoadMessage() {
    wx.showLoading({
      title: '加载中',
    })
    this.loadNotice(this.data.new_notice_page + 1)
    wx.hideLoading({})
  },
  flush() {
    // this.onLoad();
    this.setData({
      hideHeader: false
    })
    setTimeout(() => {
      this.setData({
        hideHeader: true
      })
    }, 1000);
  },
  getTime() { //获取时间
    var date = new Date();

    // var year = date.getFullYear();
    // var month = date.getMonth();
    // var day = date.getDate();

    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();

    //这样写显示时间在1~9会挤占空间；所以要在1~9的数字前补零;
    if (hour < 10) {
      hour = '0' + hour;
    }
    if (minute < 10) {
      minute = '0' + minute;
    }
    if (second < 10) {
      second = '0' + second;
    }
    var x = date.getDay(); //获取星期
    return hour + ':' + minute + ':' + second
  },
  getNewArticle(index) {
    // console.log("page: ", index)
    let that = this;
    /**
     * 获取最新的几篇文章
     */
    if (this.data.new_end) {
      return;
    }

    // console.log("Storage.get.campusId：" + getApp().Storage.get("campusId"))
    let campusId = getApp().Storage.get("campusId")
    if (campusId == null || campusId.length <= 0) {
      campusId = 1
    }
    getApp().requestWithoutToken.get('/api/getNewArticle/' + index + '/' + campusId).then(result => {
      const {
        list = []
      } = result.data
      if (index == 1) {
        that.setData({
          new_article: list
        })
      } else {
        that.setData({
          new_article: that.data.new_article.concat(list),
          new_page: result.data.pageNum
        })
      }
      if (!result.data.hasNextPage) {
        // if (that.data.new_page >= result.data.pages) {
        that.setData({
          new_end: true
        })
      }
    });
  },
  getAllLikeArticle(index) {
    // console.log("likePage: ", index)
    let that = this;
    /**
     * 获取最新的几篇文章
     */
    if (this.data.new_likeArticle_end) {
      return;
    }

    let campusId = getApp().Storage.get("campusId")
    if (campusId == null || campusId.length <= 0) {
      campusId = 1
    }
    getApp().requestWithoutToken.get('/api/getAllLikeArticle/' + index + '/' + campusId).then(result => {
      const {
        list = []
      } = result.data
      // console.log(likeSet,list)
      if (index == 1) {
        that.setData({
          new_likeArticle: list,
          "loadShow[2]": 0
        })
      } else {
        that.setData({
          new_likeArticle: that.data.new_likeArticle.concat(list),
          new_likeArticle_page: result.data.pageNum,
          "loadShow[2]": 0
        })
      }
      if (!result.data.hasNextPage) {
        // if (that.data.new_likeArticle_page >= result.data.pages) {
        that.setData({
          new_likeArticle_end: true
        })
      }
      // result.data.list.forEach(async ({ articleId }, i) => {
      //   const { data } = await getApp().requestWithToken.get('/getLikeArticle/' + articleId)
      //   result.data.list[i].liked = data;
      // })
    });
  },
  //加载新消息
  loadNotice(index) {
    // console.log("noticePage: ", index)
    if (this.data.new_notice_end) {
      return;
    }

    let that = this;
    getApp().requestWithToken.get('/getNoticeMessage/' + index).then(result => {
      if (that.data.new_notice_page == 1) {
        that.setData({
          new_notice: result.data.list
        })
      } else {
        that.setData({
          new_notice: that.data.new_notice.concat(result.data.list),
          new_notice_page: result.data.pageNum
        })
      }
      if (!result.data.hasNextPage) {
        // if (that.data.new_notice_page >= result.data.pages) {
        that.setData({
          new_notice_end: true
        })
        return
      }
    });
  },
  checkLogin() { //检查登录
    let userInfo = getApp().Storage.get("userInfo");
    let token = getApp().Storage.get("token");
    if (userInfo == "" || userInfo == null || token == "" || token == null) {
      this.setData({
        isShow: true,
        userInfo: null
      })
      return false;
    } else {
      this.setData({
        userInfo: userInfo,
        isShow: false
      })
      return true
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },





  skipSearchSchool() {
    wx.navigateTo({
      url: '/pages/index/searchSchool/searchSchool'
    })
  },
  skipSearchArticle() {
    wx.navigateTo({
      url: '/pages/index/searchArticle/searchArticle'
    })
  },
  refreshSchoolInfo(campusId) {

    if (campusId == null || campusId.length <= 0) {
      campusId = 1
    }

    getApp().requestWithToken.get('/campus/get/' + campusId ?? 1).then(result => {
      // console.log(result.data.campusLogo)
      let campusLogo = "https://funcampus.oss-cn-guangzhou.aliyuncs.com/" + result.data.campusLogo

      function convertToShort(num) {
        if (num > 10000) {
          return (num / 10000).toString() + 'w';
        } else if (num > 1000) {
          return (num / 1000).toString() + 'k';
        } else {
          return num.toString();
        }
      }

      let totalUser = convertToShort(result.data.totalUser)
      let totalArticle = convertToShort(result.data.totalArticle)

      this.setData({
        "campusLogo": campusLogo,
        "campusName": result.data.campusName,
        "totalUser": totalUser,
        "totalArticle": totalArticle
      })
    })
  }
})